#ifndef HPCDATABASE_H
#define HPCDATABASE_H
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <mysql/mysql.h>
#include <iostream>
#include <vector>
#include <HPCLogDevice.h>
#include <HPCSensorValue.h>
#include <HPCStation.h>
#include <HPCUnit.h>
#include <HPCSensor.h>
#include <pthread.h>
#include <boost/property_tree/ptree.hpp>

using namespace std;

class HPCDatabase : public HPCLogDevice
{
public:
    HPCDatabase(string host, string usr, string pwd, string dbname, string cacheFile);
    virtual ~HPCDatabase();

    void checkStation();
    virtual inline int DBState() const
    {    cout << "DBState: " << this->m_State << endl;
         return this-> m_State;}

    virtual void createUnits (HPCStation& station);

    virtual void OnLog( const HPCLogMessage& lm );

protected:
    virtual void createSensors (HPCUnit& unit,boost::property_tree::ptree &ptUnit);
    virtual void UnitChanged( HPCUnit* sender, HPCSensor* sensor, const HPCSensorValue& val );
    virtual void UnitAlarmed( HPCUnit* sender, HPCSensor* sensor, const HPCSensorValue& val, bool bMax, unsigned int index);

private:
    int   m_State;
    MYSQL *m_sql;
    long  m_StationId;
    string m_StationTitle;
    string m_MacAddress;
    string m_host;
    string m_usr;
    string m_pwd;
    string m_dbName;
    boost::property_tree::ptree m_ptStationConfig;
    string m_CacheFile;
    string m_XMLConfigFile;
    pthread_mutex_t m_Lock;
    vector<HPCUnit::TConnection> m_UnitEvents;
    vector<HPCUnit::TConnection> m_UnitAlarms;

    string getMacAddres();
    unsigned int getSensorParameter (unsigned long sensId, string param);
    void getSensorAlerts (HPCSensor *sensor,boost::property_tree::ptree &ptSens);
    void writeMeasureValue(HPCSensor *sensor, const HPCSensorValue& val);
    void writeMeasureValueToDB(HPCSensor *sensor, const HPCSensorValue& val);
    void writeMeasureValueToFile(HPCSensor *sensor, const HPCSensorValue& val);
    void connectAndRegister(string host, string usr, string pwd, string dbname);
    void checkAndWriteLocalMeasureValues();
    void createUnitsFromXML(HPCStation& station);
    void createUnitsFromDB(HPCStation& station);
    void writeStationConfig ();
};

#endif // HPCDATABASE_H
